//
//  KKNetwork.m
//  Questionnaire
//
//  Created by leo on 16/1/24.
//  Copyright © 2016年 leo. All rights reserved.
//

#import "KKNetworkManager.h"


@implementation KKNetworkManager

+ (NSMutableURLRequest*)requestWithURL:(NSString *)urlString {
    
    if (urlString == nil) {
        return nil;
    }
    NSURL *url = [NSURL URLWithString: urlString];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setValue:@"application/json;charset=utf-8" forHTTPHeaderField:@"content-type"];
    [request setHTTPMethod:@"POST"];
    [request setTimeoutInterval: 15];
    
    return request;
}

#pragma mark - Post methods

+ (void)sendPostRequest:(KKNetworkRequest *)request success:(KKNetworkSuccessHandle)successful faile:(KKNetworkFaileHandle)faile {
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible: true];
    
    NSMutableURLRequest *URLRequest = [self requestWithURL: request.requestURL];
    
    NSData *postData = [request postData];
    if (postData) {
        [URLRequest setHTTPBody: postData];
    }
    
    NSURLSession *session = [NSURLSession sharedSession];
    //  子线程运行
    
    if (URLRequest == nil) {
        
        if (faile) {
            faile(@"参数有误");
        }
        
//        [[KKLoadingView sharedInstance] stopLoading];
        return;
    }
    
//    [[KKLoadingView sharedInstance] loadingViewShowTips: @"加载中..." andWithEnable: true];
    
    __weak typeof(self) weakSelf = self;
    NSURLSessionDataTask *task = [session dataTaskWithRequest: URLRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        
        //  回到主线程
        dispatch_async(dispatch_get_main_queue(), ^{
            
//            [[KKLoadingView sharedInstance] stopLoading];
            
            [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible: false];
            if (error) {
                
                NSDictionary *userInfo = error.userInfo;
                NSString *errorString = userInfo[NSLocalizedDescriptionKey];
                
                [weakSelf showResponseErrorWithRequest: request error: errorString];
                if (faile) {
                    faile(error.description);
                }
                return;
            }
            
            NSString *parserError = nil;
            KKNetworkResponse *responseObject = [KKNetworkResponse responseWithData: data request:request error: &parserError];
            
            if (responseObject == nil && parserError != nil) {
                [weakSelf showResponseErrorWithRequest: request error: parserError];
                
                if (faile) {
                    faile(parserError);
                }
            }
            else {
                if (successful) {
                    successful(responseObject);
                }
            }
        });
    }];
    
    [task resume];
}

+ (void)sendDownloadFileRequest:(KKNetworkRequest *)request success:(KKNetworkSuccessHandle)successful faile:(KKNetworkFaileHandle)faile {
    
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible: true];
    
    NSMutableURLRequest *URLRequest = [self requestWithURL: request.requestURL];
    
    NSData *postData = [request postData];
    if (postData) {
        [URLRequest setHTTPBody: postData];
    }
    
    NSURLSession *session = [NSURLSession sharedSession];
    //  子线程运行
    
    if (URLRequest == nil) {
        
        if (faile) {
            faile(@"参数有误");
        }
        
//        [[KKLoadingView sharedInstance] stopLoading];
        return;
    }
    
//    [[KKLoadingView sharedInstance] loadingViewShowTips: @"加载中..." andWithEnable: true];
    
    __weak typeof(self) weakSelf = self;
    NSURLSessionDataTask *task = [session dataTaskWithRequest: URLRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        
        //  回到主线程
        dispatch_async(dispatch_get_main_queue(), ^{
            
//            [[KKLoadingView sharedInstance] stopLoading];
            
            [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible: false];
            if (error) {
                
                NSDictionary *userInfo = error.userInfo;
                NSString *errorString = userInfo[NSLocalizedDescriptionKey];
                
                [weakSelf showResponseErrorWithRequest: request error: errorString];
                if (faile) {
                    faile(error.description);
                }
                return;
            }
            else {
                if (successful) {
                    
                    KKNetworkResponse *response = [KKNetworkResponse new];
                    response.responseObject = data;
                    successful(response);
                }
            }
        });
    }];
    
    [task resume];
}

+ (void)showResponseErrorWithRequest:(KKNetworkRequest *)request error:(NSString *)errorString {
    
    if (!request.showAlert) {
        return;
    }
    
    if (request == nil || errorString == nil) {
        
    }
    
//    [[KKAlertView shareInterce] showWithTitle: @"错误" andWithMessage: errorString andWithCancelTitle: nil andWithCancelHandle: nil andWithSureTitle: @"关闭" andWithSureHandle: nil];
}


@end
